package algorithm;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/19
 * <p>
 * \* Time: 15:50
 * <p>
 * \* Description:
 * \
 */
public class QuickSortDemo {

    static void sort(int[] arr) {
        sort(arr, 0, arr.length - 1);
    }

    private static void sort(int[] arr, int l, int r) {
        if (l >= r) return;

        //通过交换元素构建分界点
        int p = partition(arr, l, r);

        //现在arr[l - p-1] 都小于 arr[p]; arr[p-r] 都大于arr[p]
        sort(arr, l, p - 1);
        sort(arr, p + 1, r);
    }

    private static int partition(int[] arr, int l, int r) {
        if (l == r) {
            return l;
        }
        //将arr[l] 作为默认分界点 p
        int p = arr[l];
        int i = l, j = r + 1;
        while (true) {
            //保证arr[l...i]都小于p
            while (arr[++i] < p) {
                if (i == r) break;
            }
            //保证arr[j .. r]都大于p
            while (arr[--j] > p) {
                if (j == l) break;
            }
            if (i >= j) break;

            swap(arr, i, j);
        }
        swap(arr, j, l);
        return j;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{5, 6, 8, 75, 2, 1, 6, 5, 9, 11};
        sort(arr);
    }
}
